package cn.yuanqiao.web.controller.license.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GenerateQR {
    /**
     * 生成二维码的方法
     * @param content 二维码内容
     * @param path 二维码图片保存路径
     */
    public static void code(String content, ByteArrayOutputStream pngOutputStream){
        //设置二维码宽
        int width = 400;
        //设置二维码高
        int height = 400;
        //设置二维码的后缀名称
        String format = "png";
        //设置map集合要往二维码内添加的参数
        @SuppressWarnings("rawtypes")
        Map map = new HashMap();
        //设置二维码的级别
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //设置二维码中文本的编码格式
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置二维码的外边框
        map.put(EncodeHintType.MARGIN, 5);
        try {
            //创建生成二维码对象，调用方法将所需要的参数放入
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,map);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
